package com.zhang.bingmei_incomeexpenditure.config;

import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.List;
import java.util.Map;

/**
 * 自定义列宽处理器（适配 EasyExcel 2.2.10）
 */
public class CustomColumnWidthHandler implements CellWriteHandler {

    private final Map<Integer, Integer> columnWidthMap; // 列索引 -> 宽度（字符数）

    public CustomColumnWidthHandler(Map<Integer, Integer> columnWidthMap) {
        this.columnWidthMap = columnWidthMap;
    }

    // 只在单元格创建前设置列宽，其他方法空实现
    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, 
                                Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
        if (columnWidthMap == null || !columnWidthMap.containsKey(columnIndex)) {
            return;
        }
        // 设置列宽（POI单位：1/256字符，×256转换）
        Sheet sheet = writeSheetHolder.getSheet();
        sheet.setColumnWidth(columnIndex, columnWidthMap.get(columnIndex) * 256);
    }

    // 以下方法均为接口要求的空实现，无需任何逻辑
    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, 
                               Cell cell, Head head, Integer integer, Boolean aBoolean) {}

    @Override
    public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, 
                                      CellData cellData, Cell cell, Head head, Integer integer, Boolean aBoolean) {}

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, 
                                List<CellData> list, Cell cell, Head head, Integer integer, Boolean aBoolean) {}
}